package com.example.http.websocket.level3;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;

/**
 * @author 。
 */
@ServerEndpoint(value = "/content_websocket")
public class ContentWebSocket {


    /**
     * 内容集合
     */
    public static Map contentMap = new HashMap<>();


    /**
     * 创建
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) {

    }

    /**
     * 发送消息
     *
     * @param contentId
     * @throws IOException
     */
    @OnMessage
    public void sendMessage(Session session, String contentId) {
        List c = (List) contentMap.get(contentId);
        if (c == null) {
            c = new ArrayList();
        }
        c.add(session);
        //创建时把当前会话放在集合中，这样集合大小就是实时浏览人数
        contentMap.put(contentId, c);
        broadcast(c, c.size() + "");
    }

    /**
     * 关闭
     */
    @OnClose
    public void onClose(Session session) {
        Map<String, List<String>> requestParameterMap = session.getRequestParameterMap();
        //关闭时从链接获取content的ID
        List<String> contentids = requestParameterMap.get("content_id");
        if (contentids != null && contentids.size() > 0) {
            String contentId = contentids.get(0);
            List c = (List) contentMap.get(contentId);
            if (c != null) {
                //从集合中移除该会话
                c.remove(session);
                contentMap.put(contentId, c);
                broadcast(c, c.size() + "");
            }

        }
    }

    /**
     * 发生错误
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }


    /**
     * 消息广播
     *
     * @param sessions
     * @param msg
     */
    public void broadcast(List<Session> sessions, String msg) {
        for (Iterator it = sessions.iterator(); it.hasNext(); ) {
            Session session = (Session) it.next();
            try {
                if (session.isOpen()) {
                    //当当前会话没有被关闭 发送消息
                    session.getBasicRemote().sendText(msg);
                } else {
                    it.remove();
                }
            } catch (IOException e) {
                e.printStackTrace();
                it.remove();
            }
        }

    }
}